package com.qh.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.qh.basic.exception.BusinessException;
import com.qh.basic.jwt.JwtUtils;
import com.qh.basic.jwt.LoginData;
import com.qh.basic.jwt.RsaUtils;
import com.qh.basic.util.AjaxResult;
import com.qh.basic.util.HttpUtil;
import com.qh.basic.util.Md5Utils;
import com.qh.basic.util.StrUtils;
import com.qh.system.domain.Menu;
import com.qh.system.domain.Permission;
import com.qh.user.constant.WxConstants;
import com.qh.user.domain.Logininfo;
import com.qh.user.domain.User;
import com.qh.user.domain.Wxuser;
import com.qh.user.dto.LoginDto;
import com.qh.user.mapper.LogininfoMapper;
import com.qh.user.mapper.UserMapper;
import com.qh.user.mapper.WxuserMapper;
import com.qh.user.service.ILogininfoService;
import com.qh.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 账号登录
     * @param loginDto
     * @return
     */
    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        //一.校验
        //1.空值校验
        if (StringUtils.isEmpty(loginDto.getAccount()) || StringUtils.isEmpty(loginDto.getPassword())){
            throw new BusinessException("信息不能为空");
        }
        //2.账号校验
        Logininfo logininfo = logininfoMapper.loadByAccount(loginDto);
        if (logininfo==null){//根据账号没有查到信息
            throw new BusinessException("账号错误");
        }
        //3.校验密码
        String salt = logininfo.getSalt();
        String inputMd5Password = Md5Utils.encrypByMd5(loginDto.getPassword() + salt);
        if (!inputMd5Password.equals(logininfo.getPassword())){
            throw new BusinessException("密码错误");
        }
        //4.校验是否禁用
        if (!logininfo.getDisable()){
            throw new BusinessException("账号已被停用，请联系管理员");
        }
        /*//二.添加到redis,并设置30分钟有效
        //1.生成一个uuid为token
        String token = UUID.randomUUID().toString();
        //2.存到redis中
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        //三.返回信息
        //为了安全，将盐值和密码置空
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("logininfo",logininfo);*/
        //二.使用jwt加密返回给前端，并设置时间我30分钟
        Map<String, Object> map = loginSuccessByHandler(logininfo);
        return map;
    }

    /**
     * 微信登录
     * @param map
     * @return
     */
    @Override
    public AjaxResult wechatLogin(Map<String, String> map) {
        //发送第二个请求参数：appid，code，secret，返回：token，openid
        //1.准备发送第二个请求的地址：后端通过httpUtil发送
        String url = WxConstants.GET_ACK_URL.replace("APPID", WxConstants.APPID).
                replace("SECRET", WxConstants.SECRET).replace("CODE", map.get("code"));

        //2.使用httpUtil后端发送请求，返回json的对象【官网查参数名字】
        String jsonStr = HttpUtil.httpGet(url);

        //3.使用fastjson将jsonStr字符串转为JSON对象
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        //通过getString方法参数key获取值【查官网】
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        //4.通过openid查t_wxuser
        Wxuser wxuser = wxuserMapper.loadByOpenid(openid);
        if (wxuser !=null){//绑定过
            //通过wxuser的user_id可以有可能查到user表的信息
            User user = userMapper.loadOne(wxuser.getUserId());
            if (user != null){//且绑定了user
                //通过user的logininfo_id可以有可能查到logininfo表的信息
                Logininfo logininfo = logininfoMapper.loadOne(user.getLogininfoId());//且同步了logininfo
                //免密登录
                Map<String, Object> resultMap = loginSuccessByHandler(logininfo);
                return new AjaxResult(true,"登录成功",resultMap);
            }
        }
        //最后，user没有查询到，第一次扫码--将token和openid响应给绑定页面
        return AjaxResult.me().setSuccess(false).setObj("?access_token="+access_token+"&openid="+openid);
    }

    /**
     * 微信绑定
     * @param map
     * @return
     */
    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");
        //1.空值校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("信息不能为空");
        }
        //2.验证码校验--错误，是否为空
        Object code = redisTemplate.opsForValue().get("binder:" + phone);
        if (code==null){
            throw new BusinessException("请填写验证码");
        }
        if (!code.toString().split(":")[0].equals(verifyCode)){
            throw new BusinessException("验证码错误");
        }
        //3.第三个请求准备
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        //4.使用httpUtil发送微信绑定请求
        String jsonStr = HttpUtil.httpGet(url);
        //5.使用fastJson处理返回的jsonStr--转换为wxuser对象
        Wxuser wxuser = jsonStr2Wxuser(jsonStr);
        //6.创建user对象和logininfo对象【电话】
        //7.添加数据库1.logininfo 2.user 3.wxuser
        //为什么去查：因为以前通过手机账号注册过，没有绑定微信。
        User user = userMapper.loadByPhone(phone);
        if (user==null){//没有绑定过--直接将电话变成一个user对象，密码随机生成
            user = phone2User(phone);
            Logininfo logininfo = user2Logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
            wxuser.setUserId(user.getId());//微信绑定用户表
        }
        wxuserMapper.save(wxuser);
        //8.免密登录-uuid和logininfo对象
        Logininfo logininfo = logininfoMapper.loadOne(user.getLogininfoId());
        Map<String, Object> resultMap = loginSuccessByHandler(logininfo);
        return new AjaxResult(true,"登录成功",resultMap);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String password = StrUtils.getComplexRandomString(16);
        String md5Password = Md5Utils.encrypByMd5(password + salt);
        user.setSalt(salt);
        user.setPassword(md5Password);
        user.setState(1);
        return user;
    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String openid = jsonObject.getString("openid");
        String nickname = jsonObject.getString("nickname");
        String headimgurl = jsonObject.getString("headimgurl");
        String unionid = jsonObject.getString("unionid");
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(openid);
        wxuser.setNickname(nickname);
        wxuser.setHeadimgurl(headimgurl);
        wxuser.setUnionid(unionid);
        return wxuser;
    }

    /**
     * 登录成功的jwt处理登录信息的方案。
     * @param logininfo
     * @return
     */
    public Map<String,Object> loginSuccessByHandler(Logininfo logininfo){
        //传递给前端的
        Map<String, Object> map = new HashMap<>();
        //需要使用jwt加密的
        LoginData loginData = new LoginData();
        //为了安全将盐值和密码置空
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        loginData.setLogininfo(logininfo);//普通用户只有登录信息
        map.put("logininfo",logininfo);
        if (logininfo.getType()==0){//管理员才有菜单和权限
            //1.设置权限
            List<String> permissions = logininfoMapper.loadPermissionByLogininfoId(logininfo.getId());
            map.put("permissions",permissions);
            loginData.setPermissions(permissions);
            //2.设置菜单
            List<Menu> menus = logininfoMapper.loadMenuByLgininfoId(logininfo.getId());
            map.put("menus",menus);
            loginData.setMenus(menus);
        }
        //加密
        try {
            //1.获取私钥
            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.
                    getClassLoader().getResource("auth_rsa.pri").getFile());
            //2.通过JwtUtils加密logindata并设置时间为30分钟
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30);
            map.put("token",jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
